<?php

namespace common\components\form\field;

use Yii;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use common\components\form\Form;
use common\components\form\Field;

/**
 * description of Boolean
 *
 * @author FireLoong
 */
class Boolean extends Field
{
    public function setup($options = [])
    {
        if ($this->setupParams) {
            $options = $this->setupParams[0] ?? $options;
        }

        $options['item'] = function ($index, $label, $name, $checked, $value) use ($options) {
            if (!isset($options['itemOptions']['labelOptions']['class'])) {
                $class = 'btn btn-' . ($checked ? ($value ? 'success' : 'danger') : 'default');
                $options['itemOptions']['labelOptions']['class'] = $class;
            }
            return Html::radio($name, $checked, array_merge([
                'value' => $value,
                'label' => $label
            ], $options['itemOptions']));
        };

        if ($this->form->validationStateOn === Form::VALIDATION_STATE_ON_INPUT) {
            $this->addErrorClassIfNeeded($options);
        }

        $this->addAriaAttributes($options);
        $this->adjustLabelFor($options);
        $this->_skipLabelFor = true;

        $options['class'] = (isset($options['class']) ? $options['class'] . ' ' : '') . 'btn-group btn-boolean';

        $items = [1 => Yii::t('common', 'YES'), 0 => Yii::t('common', 'NO')];

        $this->parts['{input}'] = Html::activeRadioList($this->model, $this->attribute, $items, $options);

        $css = <<<CSS
.btn-boolean{width:200px;}.btn-boolean>label{width:50%;outline:none !important;}
.btn-boolean > .btn input[type="radio"]{position: absolute;clip: rect(0,0,0,0);pointer-events: none;}
CSS;
        $this->form->view->registerCss($css);
        $js = <<<JS
$('.btn-boolean > .btn').on('click', function() {
    var changed = true;
    var parent = $(this).closest('.btn-boolean');
    var input = $(this).find('input');
    if (input.prop('checked')) changed = false;
    parent.find('.btn').removeClass('btn-success').removeClass('btn-danger').addClass('btn-default');
    if (input.prop('checked')){
        var val = input.val();
        if (val == 1){
            $(this).removeClass('btn-default').addClass('btn-success');
            input.prop('checked', true);
        }else if(val == 0){
            $(this).removeClass('btn-default').addClass('btn-danger');
            input.prop('checked', true);
        }
    }
    if(changed) input.trigger('change');
})
JS;
        $this->form->view->registerJs($js);

        return $this;
    }
}
